﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace DingTalkAgent.Web.Controllers
{
    [Common.Filter.AuthorizeFilter]
    public class RolesController : Common.adminBaseController
    {
        public SqlData.Roles dh = new SqlData.Roles();
        private DingTalkAgent.SqlData.SysPage ISysPage = new SqlData.SysPage();
        private DingTalkAgent.SqlData.SysAction ISysAction = new SqlData.SysAction();
        private DingTalkAgent.SqlData.SysNav ISysNav = new DingTalkAgent.SqlData.SysNav();
        [Common.Filter.ViewPage]
        /// <summary>
        /// 角色列表
        /// </summary>
        /// <returns></returns>
        public ActionResult List()
        {
            try
            {
                int records = 0;

                if (Request.IsAjaxRequest())
                {
                    int rows = Convert.ToInt32(Request["rows"] == null ? "10" : Request["rows"].ToString());
                    int page = Convert.ToInt32(Request["page"] == null ? "1" : Request["page"].ToString());
                    var keyword = Request["keyword"] == null ? "" : Request["keyword"].ToString();

                    int Parent_ID = Request.Form["Parent_ID"] == null ? 0 : Convert.ToInt32(Request.Form["Parent_ID"].ToString());

                    List<DingTalkAgent.Model.Roles> list = dh.GetPageList(page, rows, out records, keyword);
                    var pagelist = new Models.Roles_Page()
                    {
                        records = records,
                        page = page,
                        pagesize = rows,
                        List = list,
                    };

                    return Json(pagelist);
                }

                return View();
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        /// <summary>
        /// 添加角色
        /// </summary>
        /// <returns></returns>
        public ActionResult Add()
        {
            return View();
        }
        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Add(Model.Roles model)
        {
            try
            {
                if (string.IsNullOrEmpty(model.Name))
                {
                    return Content("姓名不可以为空");
                }
                if (string.IsNullOrEmpty(model.Remark))
                {
                    return Content("请输入角色的描述");
                }
                model.Active = 1;
                model.User_ID = _view_Admin_Info.UserID;
                if (dh.Add(model) > 0)
                {
                    //操作记录
                    Models.Operation.Add(_view_Admin_Info.UserID.ToString(), "注册驾驶员", "成功注册驾驶员:", _view_Admin_Info.Name);
                    return Content("true");
                }
                else
                {
                    return Content("保存信息失败!");
                }
            }
            catch (Exception ex)
            {
                return View();
            }
        }
        [Common.myCommon]
        /// <summary>
        /// 启用、禁用用户角色
        /// </summary>
        /// <param name="ID"></param>
        /// <param name="Active"></param>
        /// <returns></returns>
        public ActionResult EditStatus(int ID, int Active)
        {
            try
            {
                var l = dh.GetModel(ID);
                if (l == null)
                {
                    return Content("找不到角色信息！");
                }
                if (l.Active == 1)
                {
                    Active = 0;
                    dh.UpdateStatus(ID, Active);
                    //操作记录
                    Models.Operation.Add(_view_Admin_Info.ID.ToString(), "修改状态", "修改状态成功", _view_Admin_Info.Name);
                    return RedirectToAction("List", "Roles");
                }
                else
                {
                    Active = 1;
                    dh.UpdateStatus(ID, Active);
                    //操作记录
                    Models.Operation.Add(_view_Admin_Info.ID.ToString(), "修改状态", "修改状态成功", _view_Admin_Info.Name);
                    return RedirectToAction("List", "Roles");
                }
            }
            catch (Exception ex)
            {
                //错误日志
                Models.ErrorLog.Add(_view_Admin_Info.UserID, "/Roles/Edit", ex.Message, _view_Admin_Info.Name);
                ViewBag.Msg = "查找的信息不存在!";
                return View("Error");
            }
        }
        /// <summary>
        /// 取得一个角色信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Edit(int id)
        {
            try
            {
                var m = dh.GetModel(id);
                if (m == null)
                {
                    return Content("找不到角色信息！");
                }
                return View(m);
            }
            catch (Exception ex)
            {
                //错误日志
                Models.ErrorLog.Add(_view_Admin_Info.UserID, "/DrivingUser/Edit", ex.Message, _view_Admin_Info.Name);
                ViewBag.Msg = "查找的信息不存在!";
                return View("Error");
            }
        }
        /// <summary>
        /// 修改角色
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Edit(Model.Roles model)
        {
            try
            {
                if (string.IsNullOrEmpty(model.Name))
                {
                    return Content("姓名不可以为空");
                }
                model.User_ID = _view_Admin_Info.UserID;
                if (dh.Update(model))
                {
                    //操作记录
                    Models.Operation.Add(_view_Admin_Info.UserID.ToString(), "修改角色", "成功修改角色:", _view_Admin_Info.Name);
                    return Content("true");
                }
                else
                {
                    return Content("保存信息失败！");
                }
            }
            catch (Exception ex)
            {
                //错误日志
                Models.ErrorLog.Add(_view_Admin_Info.UserID, "/Roles/Edit", ex.Message, _view_Admin_Info.Name);
                return Content(ConfigHelper.getErrorMsg);
            }
        }
        /// <summary>
        /// 删除单个角色
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Delete(int id)
        {
            try
            {
                if (dh.Delete(id))
                {
                    //操作记录
                    Models.Operation.Add(_view_Admin_Info.UserID.ToString(), "删除角色", "成功删除角色:id:" + id, _view_Admin_Info.Name);
                    return Content("true");
                }
                else
                {
                    return Content("删除信息失败!");
                }
            }
            catch (Exception ex)
            {
                //错误日志
                Models.ErrorLog.Add(_view_Admin_Info.UserID, "/Roles/Delete", ex.Message, _view_Admin_Info.Name);
                return Content(ConfigHelper.getErrorMsg);
            }
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="id"></param>
        /// <param name="collection"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Deletes(string IDs)
        {
            try
            {
                //
                IDs = Discuz.Common.Utils.ChkSQL(IDs).TrimEnd(',');
                if (dh.Deletes(IDs))
                {
                    //操作记录
                    Models.Operation.Add(_view_Admin_Info.UserID.ToString(), "批量删除角色", "成功批量删除角色:ids:" + IDs, _view_Admin_Info.Name);
                    return Content("true");
                }
                else
                {
                    return Content("删除信息失败!");
                }
            }
            catch (Exception ex)
            {
                //错误日志
                Models.ErrorLog.Add(_view_Admin_Info.UserID, "/Roles/Deletes", ex.Message, _view_Admin_Info.Name);
                return Content(ConfigHelper.getErrorMsg);
            }
        }

        //角色权限
        [Common.Filter.ViewPage]
        public ActionResult RolePower(int id = 1)
        {
            var RoleList = dh.IEnumGetList("Active=1").ToList();
            var m = new Models.RolePower()
            {
                RoleList = RoleList
            };
            return View(m);
        }
        /// 获取栏目
        [Common.myCommon]
        public ActionResult Nav_Action(int RoleID)
        {
            var NavL = ISysNav.IEnumGetList("", RoleID).ToList();
            var Action = ISysAction.IEnumGetList("", RoleID).ToList();
            var m = new Models.RolePower()
            {
                RoleList = null,
                SysNavList = NavL,
                SysActionList = Action
            };
            return View(m);
        }

        //角色权限保存
        [HttpPost]
        public ActionResult RolePowerX(FormCollection forms)
        {
            try
            {

                var RoleID = int.Parse(forms["RoleID"].ToString());

                List<int> ints = new List<int>();
                Dictionary<int, int> datapower = new Dictionary<int, int>();
                int dpkey, dpvalue;

                foreach (var f in forms.Keys)
                {
                    if (f.ToString() == "RoleID")
                    {
                        continue;
                    }
                    else if (f.ToString().IndexOf("checkbox_") > -1)
                    {
                        ints.Add(int.Parse(forms[f.ToString()]));
                    }
                    else if (f.ToString().IndexOf("radio_") > -1)
                    {
                        dpkey = int.Parse(f.ToString().Split('_')[1]);
                        dpvalue = int.Parse(forms[f.ToString()]);
                        datapower.Add(dpkey, dpvalue);
                    }

                }
                int result = dh.SaveCheckboxPower(RoleID, ints);
                int dpresult = dh.SaveRadioPower(RoleID,datapower);
                if (result > 0)
                {
                    //操作记录
                    Models.Operation.Add(_view_Admin_Info.UserID.ToString(), "Role权限分配", "权限分配Role:id:" + RoleID, _view_Admin_Info.Name);
                    return Content("true");
                }
                else
                {
                    return Content("权限分配失败！！");
                }
            }
            catch (Exception ex)
            {
                //错误日志
                Models.ErrorLog.Add(_view_Admin_Info.UserID, "/Role/RolePowerX", ex.Message, _view_Admin_Info.Name);
                return Content(ConfigHelper.getErrorMsg);
            }

        }

        [Common.myCommon]
        //更改状态
        public ActionResult Check(int ID, int status)
        {
            try
            {
                if (dh.UpdateStatus(ID, status))
                {
                    //操作记录
                    Models.Operation.Add(_view_Admin_Info.UserID.ToString(), "状态变更Admin_Info", "成功状态变更Admin_Info:", _view_Admin_Info.Name, "");
                    return Content("1");
                }
                else
                {
                    return Content("0");
                }
            }
            catch (Exception ex)
            {
                //错误日志
                Models.ErrorLog.Add(_view_Admin_Info.UserID, "/AdminInfo/Check", ex.Message, _view_Admin_Info.Name, "");
                return Content("-1");
            }
        }
    }

}